<template>
  <div class="flowpath-container">
    <div>
      <div class="mb20">
        <!-- <span class="color_494949 ft12 pr5 w70">{{ translate('公司名称') }}：</span> -->
        <!-- <el-autocomplete
          v-model="searchInfo"
          class="inline-input mr10"
          :fetch-suggestions="querySearch"
          placeholder="选择单位"
          @select="handleSelect"
        /> -->
        <!-- <el-input
          v-model="searchInfo"
          class="w192 mr10"
          :placeholder="translate('请输入公司名称')"
        /> -->
        <!-- <span class="color_494949 ft12 pr5 w70">{{ translate('部门名称') }}：</span>
        <el-input
          v-model="searchInfo2"
          class="w192 mr10"
          :placeholder="translate('请输入部门名称')"
        /> -->
        <span class="color_494949 ft12 pr5 w70">{{ translate('单号') }}：</span>
        <el-input
          v-model="searchInfo1"
          class="w192 mr10"
          :placeholder="translate('请输入单号')"
        />
        <span class="color_494949 ft12 pr5 w70">{{ translate('计划描述') }}：</span>
        <el-input
          v-model="searchInfo3"
          class="w192 mr10"
          :placeholder="translate('请输入计划描述')"
        />
        <span class="color_494949 ft12 pr5 w70">{{ translate('审核状态') }}：</span>
        <el-select
          v-model="Remark"
          class="w192"
          :placeholder="translate('请选择')"
         >
          <el-option
            v-for="item in RemarkArry"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
          </el-select>
          <span class="color_494949 ft12 pr5 w70 ml10">{{ translate('物料编码') }}：</span>
          <el-input
            v-model="searchitemCode"
            class="w192 mr10"
            :placeholder="translate('请输入物料编码')"
          />
      </div>
      <div>
        <span class="w70 color_494949 ft12 pr5 mb10">{{ translate('创建时间') }}：</span>
              <el-date-picker
                v-model="searchInfo4"
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
              />
        <el-button class="settingBtn ml10" type="primary" @click="getList">
          {{ translate('查询') }}
        </el-button>
        <el-button class="settingBtn mr10" type="primary" @click="resetFn">
          {{ translate('重置') }}
        </el-button>
      </div>
      <div class="add">
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="addFn"
          plain
        >
          {{ translate('新增') }}
        </el-button>
         <el-upload
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :action="action"
          :before-upload="beforeUpload"
          class="ml-upload"
          :headers="headers"
          name="fileInput"
          :on-error="handleError"
          :on-success="handleSuccess"
          :show-file-list="false"
        >
          <ElButton type="primary" @click="uploadFn()" plain>
            {{ translate('导入') }}
          </ElButton>
        </el-upload>
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="exportFn"
          plain
        >
          {{ translate('导出') }}
        </el-button>
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="withdrawFn"
          plain
        >
          {{ translate('撤回') }}
        </el-button>
        <!-- <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="InputCodeFn"
          plain
        >
          {{ translate('录入单号') }}
        </el-button> -->
      </div>
      <el-table
          :data="tableData"
          v-loading="loading"
          :row-class-name="tableRowClassName"
          :row-key="getRowKey"
          @selection-change="handleSelectionChange"
          >
        <el-table-column prop="value" type="selection" width="55" />
        <el-table-column :label="translate('单号')">
          <template #default="{ row }">
            <div>
              <span class="iconcolor1">{{ row.DPNo }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.DPNo)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('需求计划号')" min-width="100">
          <template #default="{ row }">
            <div>
              <span class="iconcolor1">{{ row.SourceBillNo }}</span>
              <vab-icon v-if="row.SourceBillNo" icon="file-copy-line" @click="copyToClipboard(row.SourceBillNo)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('计划描述')">
          <template #default="{ row }">
            <div>
              <span>{{ row.PlanDescription }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('计划类型')" prop="PlanType" />
        <el-table-column :label="translate('计划类别')" prop="PlanCategory" />
        <!-- <el-table-column :label="translate('计划来源')" prop="PlanSource" />
        <el-table-column
          :label="translate('公司')"
          prop="ComName"
          show-overflow-tooltip
        /> -->
        <el-table-column
          :label="translate('需求部门')"
          prop="DemandDept"
          show-overflow-tooltip
        />
        <!-- <el-table-column
          :label="translate('工厂')"
          prop="FactoryName"
        /> -->
        <el-table-column
          :label="translate('移动类型')"
          prop="MovementType"
          show-overflow-tooltip
        />
        <!-- <el-table-column
          :label="translate('移动类型描述')"
          prop="MovementDescription"
          show-overflow-tooltip
          min-width="120"
        /> -->
        <!-- <el-table-column
          :label="translate('是否紧急')"
          prop="IsUrgent‌"
          show-overflow-tooltip
        /> -->
        <!-- <el-table-column
          :label="translate('紧急理由')"
          prop="Urgent‌Reason"
          show-overflow-tooltip
        /> -->
        <el-table-column :label="translate('库存类')">
          <template #default="{ row }">
            <div>
             {{ row.StockCategory }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column
          :label="translate('无码计划')"
          prop="NoCodePlan"
          show-overflow-tooltip
        /> -->
        <!-- <el-table-column
          :label="translate('科目分配类别')"
          prop="CourseCategory"
          show-overflow-tooltip
          min-width="120"
        /> -->
        <el-table-column :label="translate('审核状态')">
          <template #default="{ row }">
            <div>
              <el-tag type="success" v-if="row.AuditStatus.includes('已审核')">{{ row.AuditStatus }}</el-tag>
              <el-tag type="danger" v-if="row.AuditStatus.includes('已结束')">{{ row.AuditStatus }}</el-tag>
              <el-tag v-if="row.AuditStatus.includes('流转中')">{{ row.AuditStatus }}</el-tag>
              <el-tag type="info" v-if="row.AuditStatus && row.AuditStatus !== '已审核' && row.AuditStatus !== '已结束' && !row.AuditStatus.includes('流转中')">{{ row.AuditStatus }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="translate('创建时间')"
          prop="CreateDate"
          show-overflow-tooltip
          min-width="200"
          header-align="left"
        />
        <el-table-column
          :label="translate('创建人')"
          prop="CreateUserName"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('备注')">
          <template #default="{ row }">
            <div class="colorBlue">
              {{row.Remark}}
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('操作')" width="300">
          <template #default="{ row }">
            <el-button plain size="small" type="primary" @click="examineFn(row)">
              {{ translate('审核') }}
            </el-button>
            <!-- <el-button plain size="small" type="primary" @click="FexamineFn(row)">
              {{ translate('撤回') }}
            </el-button> -->
            <el-button
              v-if="MenuAuths('edit')"
              plain
              size="small"
              type="primary"
              @click="detailFn(row)"
            >
              {{ translate('编辑') }}
            </el-button>
            <el-button
              v-if="MenuAuths('edit')"
              plain
              size="small"
              type="primary"
              @click="InputCodeFn(row)"
            >
              {{ translate('录入单号') }}
            </el-button>
            <!-- <el-button plain size="small" type="primary" @click="printFn(row)" :disabled="row.BillStatus==='作废'?true:false">
              {{ translate('打印') }}
            </el-button> -->
            <!-- <el-button plain size="small" type="primary" @click="ZFFn(row)">
              {{ translate('作废') }}
            </el-button> -->
            <el-button
              v-if="MenuAuths('delete')"
              plain
              size="small"
              type="danger"
              @click="deletedFn(row)"
            >
              {{ translate('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          :current-page="pageNo"
          :layout="layout"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="translate('计划上报详情')"
      width="1340px"
      @close="closeFn"
      :close-on-click-modal="false"
    >
      <i v-if="status === 1" class="iconfont icon-shenhezhong iconcommon"></i>
      <i v-if="status === 2" class="iconfont icon-yishenhe iconcommon2"></i>
      <detail
        :agreementlist="agreementList"
        :chileddetail="chileddetail"
        :extralist="Extralist"
        :form="form"
        fromtype="goodslist"
        :purchaselist="PurchaseList"
        :supplierdata="SupplierData"
        :whdata="WHdata"
        @changelist="changeList"
        @deletedchild="deletedchild"
        @changeextralist="changeExtralist"
      />
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ translate('取消') }}
        </el-button>
        <el-button :disabled="isclick" type="primary" @click="submit">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogVisible1"
      :before-close="handleClose1"
      :title="translate('录入单号')"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="flex_align">
        <span class="txr">单号：</span>
        <span>{{ dpNo }}</span>
      </div>
      <div class="flex_align">
        <span class="txr">需求计划号：</span>
        <el-input
          v-model="sourceBillNo"
          class="w192 mr10"
          :placeholder="translate('请输入需求计划号')"
        />
      </div>
      <template #footer>
        <el-button @click="handleClose1">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="confirm1">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <wordflow
      :drawershow="isdrawershow"
      :formid="formId"
      :nodelist="nodeList"
      @handclose="handleClose"
    />
  </div>
</template>

<script>
  import {
    planReportData,
    planDelData,
    planUpdateData,
    planAddData,
    planDetail,
    agreePageData,
    Wms_PurchaseList,
    startflow,
    auditwms,
    getinstance,
    WHGetPageData,
    Wms_ItemPlanDown,
    PlanExportNew,
    CheckPrint,
    GetDetailPagePrintData,
    BinDingItemsJson,
    Cancel_AuditDemandPlan,
    withdraw,
    EditERPNo,
    stcheck,
  } from '@/api/form'
  import detail from './components/detail'
  import wordflow from '@/views/components/wordflow/index'
  import print from './components/print'
  import { MenuAuth } from '~/src/utils/permission'
  import VabPrint from '@/plugins/VabPrint'
  import { translate } from '@/i18n'
  import { parseTime } from '@/utils'
  import { baseURL } from '@/config'
  import { useUserStore } from '@/store/modules/user'
  const userStore = useUserStore()
  const { token } = useUserStore()
  const { realname } = storeToRefs(userStore)
  export default defineComponent({
    name: 'Flowpath',
    components: { detail, wordflow, print },
    data() {
      return {
        tableData: [],
        searchInfo: '',
        searchInfo1: '',
        searchInfo2: '',
        searchInfo3: '',
        searchInfo4: [],
        searchitemCode: '',
        wheres: '',
        total: 0,
        pageNo: 1,
        pageSize: 20,
        action: '',
        headers: '',
        dialogVisible: false,
        dialogVisible1: false,
        enabled: 0,
        DetailPageData: {},
        chileddetail: [],
        chiledPrintdetail: [],
        Extralist: [],
        isclick: false,
        submitType: 'add',
        layout: 'total, sizes, prev, pager, next, jumper',
        deleList: [],
        MenuAuths: '',
        tableRef: null,
        isPrint: false,
        loading: true,
        agreementList: [],
        PurchaseList: [],
        isdrawershow: false,
        nodeList: {},
        formId: '',
        status: -1,
        WHdata: [],
        PBMID: '',
        Remark: '',
        dpNo: '',
        sourceBillNo: '',
        selectArr: [],
        RemarkArry: [
          {
            label: '全部',
            value: '全部',
          },
          {
            label: '草稿',
            value: '0',
          },
          {
            label: '流转中',
            value: '1',
          },
          {
            label: '已结束',
            value: '2',
          },
          {
            label: '被返回',
            value: '-1',
          },
          {
            label: '被拒绝',
            value: '-2',
          },
          {
            label: '其它',
            value: '其它',
          }
        ],
        form: {
          PlanDescription: '',
          PlanType: 'T001',
          PlanCategory: '',
          PlanSource: '',
          ComName: '',
          DemandDept: '',
          FactoryName: '',
          MovementType: '',
          MovementDescription: '',
          IsUrgent‌: '',
          Urgent‌Reason: '',
          NoCodePlan: '',
          CourseCategory: '',
        },
        rules: {
          code: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入工号'),
            },
          ],
          Account: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入登录账号'),
            },
          ],
          workFlowName: [
            {
              required: true,
              trigger: 'blur',
              message: translate('请输入账号名称'),
            },
          ],
        },
      }
    },
    created() {
      this.MenuAuths = MenuAuth
      this.searchInfo4 = [this.getFirstDayOfMonthFormatted(),this.getLastDayOfMonth()]
      this.getList()
      this.BinDingItemsJson()
    },
    methods: {
      getLastDayOfMonth() {
      // 创建一个当前日期的副本
          let date = new Date();

          // 设置日期为下个月的第一天（这样可以跳过本月所有日期）
          date.setDate(1);
          date.setMonth(date.getMonth() + 1);
          date.setDate(0); // 这会将日期设置为上一个月的最后一天

          // 格式化日期为 YYYY-MM-DD
          let year = date.getFullYear();
          let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1
          let day = String(date.getDate()).padStart(2, '0');

          return `${year}-${month}-${day}`;
      },
      getFirstDayOfMonthFormatted() {
            const today = new Date(); // 获取当前日期
            const year = today.getFullYear(); // 获取年份
            const month = today.getMonth(); // 获取月份（注意：0表示1月，11表示12月）
            const date = 1; // 设置日期为1（即当前月份的第一天）

            // 创建日期对象
            const firstDay = new Date(year, month, date);

            // 手动格式化日期为 YYYY-MM-DD
            const formattedDate = `${year.toString().padStart(4, '0')}-${(month + 1).toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;
            return formattedDate;
        },
      tableRowClassName({ row, rowIndex }) {
        row.row_index = rowIndex
      },
      handleSelectionChange(e) {
        this.selectArr = e
      },
      getRowKey(row) {
        return row.PBMID
      },
      async uploadFn() {
        this.loading = true
        this.headers = this.headers = {
          Authorization: `Bearer ${token}`,
        }
        this.action = `${baseURL}/Wms_DemandPlanBillMaster/ImportDemandPlan?tablename=DemandPlan`
      },
      handleError(data) {
        console.log(data)
        this.loading = false
      },
      handleSuccess(data) {
        console.log(data)
        this.loading = false
        if (data.code === '200') {
          this.$message({
            type: 'success',
            message: data.message,
          })
          this.getList()
        } else {
          this.$message({
            message: data.message,
            type: 'error',
          })
        }
      },
      resetFn() {
        this.searchInfo = ''
        this.searchInfo1 = ''
        this.searchInfo2 = ''
        this.searchInfo3 = ''
        this.searchitemCode = ''
        this.Remark = '全部'
        this.pageNo = 1
        this.pageSize = 20
        this.getList()
      },
      withdrawFn() {
        if(this.selectArr.length<=0){
          this.$message({
            message: translate('请选择要撤回的单据'),
            type: 'warning',
          })
          return
        }else {
          this.$confirm(translate('确认撤回流转中订单吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            console.log(this.selectArr)
            this.withdraws()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消删除'),
            })
          })
        }
      },
      async withdraws() {
        const formIdArr = []
        this.selectArr.map((item,index) =>{
             formIdArr.push(
              {
                keyValue: item.DPBMId,
                workFlowCode: 'Wms_DemandPlanBillMaster'
              }
             )
        })
        const params = formIdArr
        const data = await withdraw(params)
        if(data.Code === '200'){
          this.$message({
            message: translate('已撤回流转中订单'),
            type: 'success',
          })
          this.getList()
        }else {
          this.$message({
            message: data.Message,
            type: 'error',
          })
        }
        console.log(data)
      },
      async ZFFn(row) {
        this.formId = row.DPBMId
          this.$router.push({
            path: '/table/detail',
            query: {
              formId: this.formId,
              formcode: 'Wms_PickingBillMaster',
              type: 'zf',
              statusSH: row.BillStatus
            },
        })
      },
      InputCodeFn(row) {
        this.dpNo = row.DPNo
        this.sourceBillNo = ''
        this.dialogVisible1 = true
      },
      handleClose1() {
        this.dialogVisible1 = false
      },
      async confirm1() {
          const params = {
                dpbmId: this.formId,
                dpNo: this.dpNo,
                sourceBillNo: this.sourceBillNo
          }
          const data = await EditERPNo(params)
          if(data.result.code === '200') {
            this.$message({
            message:'保存成功',
            type:'success',
          })
          this.dialogVisible1 = false
          }else {
            this.$message({
            message: data.result.message,
            type:'error',
          })
          }
      },
      //复制标识
      async copyToClipboard(val) {
        if (navigator.clipboard && window.isSecureContext) {
          try {
          console.log(navigator.clipboard)
          console.log(window.isSecureContext)
          await navigator.clipboard.writeText(val)
          this.$message({
            message:'复制成功',
            type:'success',
          })
          } catch (err) {
            this.$message({
            message:'复制失败',
            type:'error',
          })
          }

        }else {
          // 创建text area
        const textArea = document.createElement("textarea")
        textArea.value = val
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute"
        textArea.style.opacity = 0
        textArea.style.left = "-999999px"
        textArea.style.top = "-999999px"
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()

        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? res() : rej()
          textArea.remove()
        }).then(() => {
          this.$message({
              message: "复制成功",
              type: "success",
            })
          }).catch((err) => {
            this.$message({
              message: "复制失败",
              type: "error",
            })
          })
        }

      },
      exportFn() {
        if(this.selectArr.length<=0){
          this.$message({
            message: translate('请选择要导出的单据'),
            type: 'warning',
          })
          return
        }else {
          this.$confirm(translate('确认导出选中的单据吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            console.log(this.selectArr)
            this.loading = true
            this.download()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消导出'),
            })
          })
        }
      },
      // 下载物资表
      async download() {
        const formIdArr = []
        this.selectArr.map((item,index) =>{
             formIdArr.push(
              {
                keyValue: item.DPBMId,
              }
             )
        })
        const params = formIdArr
        const data = await PlanExportNew(params)
        const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
        const blob = new Blob([data])
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        this.loading = false
        link.download = `${this.selectArr[0].DPNo}${time}.xlsx`
        link.href = url
        link.click()
      },
      translate(row) {
        return translate(row)
      },
      handleClose() {
        this.isdrawershow = false
      },
      async FexamineFn(row) {
        this.$confirm(translate('确认撤回该笔订单吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            this.CancelAuditDemandPlan(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消删除'),
            })
          })
      },
      async CancelAuditDemandPlan(row) {
            const params = {
              formId: row.DPBMId
            }
            const data = await Cancel_AuditDemandPlan(params)
            if(data.result.code === '200') {
              this.$message({
                message: translate('操作成功'),
                type: 'success',
              })
              await this.getList()
            }else {
              this.$message({
                message: translate(data.result.message),
                type: 'error',
              })
            }

      },
      async examineFn(row) {
        const params = {
          keyValue: row.DPBMId,
          code: 'Wms_DemandPlanBillMaster',
          formUrl: 'Wms_DemandPlanBillMaster',
          flowData: null,
        }
        const data = await startflow(params)
        if (data.code === '200') {
          this.auditwms('Wms_DemandPlanBillMaster', row.DPBMId)
          this.formId = row.DPBMId
          this.$router.push({
            path: '/table/detail',
            query: {
              formId: this.formId,
              formcode: 'Wms_DemandPlanBillMaster',
              statusSH: row.AuditStatus
            },
          })
        }
      },
      async auditwms(Code, id) {
        const params = {
          code: Code,
          keyValue: id,
        }
        const data = await auditwms(params)
        if (data.code === '200') {
          this.nodeList = data.data
          this.isdrawershow = true
        } else {
          this.$message({
            message: data.message,
            type: 'error',
          })
        }
      },
      async printFn(row) {
        this.form = row
        this.PBMID = row.PBMID
        await this.CheckPrintDetail()
      },
      async CheckPrintDetail() {
            const params = {
              formId: this.PBMID
            }
            const data = await CheckPrint(params)
            if(data.result.code === '200' && data.result.status) {
              await this.GetDetailPagePrintData()
              this.isPrint = true
            }else {
              this.$message({
                type: 'warning',
                message: data.result.message,
              })
            }
      },
      async submitPrint() {
        document.title = '领料单'
        await VabPrint(this.$refs.tableRef)
        this.isPrint = false
      },
      changeExtralist(val) {
        this.Extralist = val
      },
      changeList(val) {
        this.chileddetail = val?.PurchaseOrderDetail
        this.form = {
          IBType: val.IBType,
          InComeNo: val.InComeNo,
          AcceptanceNo: val.AcceptanceNo,
          SourceBillNo: val.SourceBillNo,
          Supplier: val.Supplier,
          CCode: val.CCode,
          EntrustNo: val.EntrustNo,
          CustomizeNo: val.CustomizeNo,
          ProjectName: val.ProjectName,
          WorkBillNo: val.WorkBillNo,
          AcceptanceConclusion: val.AcceptanceConclusion,
          CategoryNumber: val.CategoryNumber,
          InComeDate: val.InComeDate,
          PurchaseNo: val.PurchaseNo,
          Description: val.Description,
          Documenter: val.Documenter,
          MaterialReceiver: val.MaterialReceiver,
          FinancialReviewer: val.FinancialReviewer,
        }
      },
      async Wms_PurchaseList() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: '',
        }
        const data = await Wms_PurchaseList(params)
        if (data.code === '200') {
          this.PurchaseList = data.data.rows
        }
      },
      async getList() {
        console.log(this.searchInfo2)
        this.loading = true
        this.wheres = ''
        if (this.searchInfo3 || this.searchInfo || this.searchInfo1 || this.searchInfo2 ||(this.searchInfo4 && this.searchInfo4 != [] && this.searchInfo4 != null && this.searchInfo4 !='null')) {
          const arr = []
          this.searchInfo.trim() !== '' &&
            arr.push({
              name: 'ComName',
              value: this.searchInfo,
              displayType: 'like',
            })
          this.searchInfo1.trim() !== '' &&
            arr.push({
              name: 'DPNo',
              value: this.searchInfo1,
              displayType: 'like',
            })
          this.searchInfo2.trim() !== '' &&
            arr.push({
              name: 'DemandDept',
              value: this.searchInfo2,
              displayType: 'like',
            })
            this.searchInfo3.trim() !== '' &&
            arr.push({
              name: 'PlanDescription',
              value: this.searchInfo3,
              displayType: 'like',
            })
          this.searchInfo4 &&
            arr.push({
              name: 'CreateDate',
              value: this.searchInfo4!=null ? this.searchInfo4[0]+' 00:00:00':'',
              displayType: 'ThanOrEqual',
            })
            arr.push({
              name: 'CreateDate',
              value: this.searchInfo4!=null ? this.searchInfo4[1]+' 23:59:59':'',
              displayType: 'LessOrequal',
            })

          this.wheres = JSON.stringify(arr)
        }

        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: this.wheres,
          export: false,
          value: this.searchitemCode,
          openid: this.Remark === '全部' ? '' : this.Remark === '其它' ? '其它' : this.Remark
        }
        const data = await planReportData(params)
        this.loading = false
        this.tableData = data.data.rows
        this.total = data.data.total
        console.log(this.tableData)
      },
      deletedchild(e) {
        this.deleList = e
        console.log(e)
      },
      async deletedFn(row) {
        this.$confirm(translate('确认删除该文件吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            this.deleted(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消删除'),
            })
          })
      },
      async deleted(row) {
        const IbmID = []
        IbmID.push(row.DPBMId)
        const params = IbmID
        const data = await planDelData(params)
        if (data.code == '200') {
          this.$message({
            message: translate('删除成功'),
            type: 'success',
          })
          await this.getList()
        }
      },
      async agreePageData() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: '',
        }
        const data = await agreePageData(params)
        this.agreementList = data.data.rows
      },
      //分页条数切换
      handleSizeChange(val) {
        this.pageSize = val
        this.getList()
      },
      //分页切换
      handleCurrentChange(val) {
        this.pageNo = val
        this.getList()
      },
      async addFn() {
        this.submitType = 'add'
        this.status = -1
        console.log(userStore.accountInfo.departmentName)
        this.form = {
          PlanDescription: '',
          PlanType: 'T001',
          PlanCategory: 'C001',
          PlanSource: 'QT',
          ComName: '2000',
          DemandDept: '',
          FactoryName: '2041',
          MovementType: '',
          MovementDescription: '',
          IsUrgent‌: '',
          Urgent‌Reason: '',
          NoCodePlan: '',
          CourseCategory: '',
        }
        await this.BinDingItemsJson()
        this.chileddetail = []
        this.Extralist = []
        this.dialogVisible = true
        this.deleList = []
      },
      async submit() {
        console.log(this.form)
        console.log(this.Extralist)
        console.log(this.chileddetail)
        if (this.status === 1 || this.status === 2) {
          const messages =
            this.status === 1
              ? '单据审核中，不允许修改！'
              : '单据已审核，不允许修改'
          this.$message({
            message: messages,
            type: 'warning',
          })
          return
        }
        // if (
        //   !this.form.PickingUnit ||
        //   !this.form.PickingDate ||
        //   !this.form.PickingPerson
        // ) {
        //   const info = !this.form.PickingUnit
        //     ? '请选择领料单位'
        //     : !this.form.PickingDate
        //     ? '请选择领料日期'
        //     : '请填写领料人'
        //   this.$message({
        //     message: info,
        //     type: 'warning',
        //   })
        //   return
        // }
        this.stchecks()
      },
      async stchecks() {
        let arrList = []
        if(this.chileddetail&&this.chileddetail.length>0) {
            this.chileddetail.map(item => {
              arrList.push(
                {
                  itemCode:item.ItemCode,
                  demandQty: item.DemandQty
                }
              )
            })
        const params = arrList
        const data = await stcheck(params)
        if(data.Code === '200') {
          if (this.submitType === 'add') {
           this.AddData()
          } else {
            this.updataSaveList()
          }
        }else {
          this.$message({
            message: data.Message,
            type: 'warning',
          })
        }
        }
      },
      closeFn() {
        this.enabled = 0
        this.form.WorkFlowID = ''
      },
      async detailFn(row) {
        this.deleList = []
        this.form = row
        this.PBMID = row.DPBMId
        this.submitType = 'edit'
        await this.getinstances(row)
        await this.planDetail(row)
        await this.BinDingItemsJson()
        await this.WHGetPageData()
        this.dialogVisible = true
      },
  querySearch(queryString, cb){
    const restaurants = this.SupplierData
    const results =
      queryString && queryString != 'null'
        ? restaurants.filter(createFilter(queryString))
        : restaurants
    console.log(results)
    // 调用 callback 返回建议列表的数据
    cb(results)
  },
  createFilter(queryString){
    return (restaurant) => {
      console.log(restaurant)
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      )
    }
  },
      async WHGetPageData() {
        const params = {
          pageNo: 1,
          pageSize: 20,
          wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
          export: true,
          moduleType: 'ModuleId',
          sort: 'SortCode',
          order: 'ASC',
          search: '',
        }
        const data = await WHGetPageData(params)
        if (data.data.rows && data.data.rows.length > 0) {
          data.data.rows.map((item) => {
            item.value = item.FullName
          })
        }
        this.WHdata = data.data.rows
      },
      async getinstances(row) {
        const params = {
          code: 'Wms_DemandPlanBillMaster',
          formId: row.DPBMId,
        }
        const data = await getinstance(params)
        if (data.code === '200') {
          this.status = data.data?.data?.status
        }
      },
      async BinDingItemsJson() {
        const params = {
           code: 'DemandDept'
        }
        const data = await BinDingItemsJson(params)
        if (data.data.data && data.data.data.length > 0) {
          data.data.data.map((item) => {
            item.value = item.fullName
          })
        }
        this.SupplierData = data.data.data
      },
      async GetDetailPagePrintData() {
        const params = {
          pageNo: 1,
          pageSize: 100,
          total: 0,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: this.PBMID,
        }
        const data = await GetDetailPagePrintData(params)
        if (data.master) {
          this.$nextTick(() => {
            this.chiledPrintdetail = data.rows
          })
        }
        if(data.msg) {
          this.$message({
            message: data.msg,
            type: 'warning',
          })
        }
        console.log(data)
      },
      async planDetail() {
        const params = {
          pageNo: 1,
          pageSize: 1000,
          total: 0,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: this.PBMID,
        }
        const data = await planDetail(params)
        if (data.master) {
          this.$nextTick(() => {
            this.chileddetail = data.rows
            this.Extralist = data.extra || []
          })
        }

      },
      async AddData() {
        this.isclick = true
        this.form.IsUrgent‌ = this.form.IsUrgent ? '是' : '否'
        const params = {
          mainData: this.form,
          detailData: this.chileddetail,
          delKeys: [],
          Extra: this.Extralist
        }
        const data = await planAddData(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
        setTimeout(() => {
          this.isclick = false
        }, 5000)
      },
      async updataSaveList() {
        this.form.IsUrgent‌ = this.form.IsUrgent ? '是' : '否'
        const params = {
          mainData: this.form,
          detailData: this.chileddetail,
          delKeys: this.deleList,
          Extra: this.Extralist
        }
        const data = await planUpdateData(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  .flowpath-container {
    .color_494949 {
      color: #494949;
    }
    .w192 {
      width: 192px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr10 {
      margin-right: 10px;
    }
    .ml10 {
      margin-left: 10px;
    }
    .add {
      margin-bottom: 10px;
      text-align: left;
    }
    .flex_align {
      height: 30px;
      line-height: 30px;
      margin: 15px;
    }
    .txr {
      display: inline-block;
      width: 100px;
      text-align: end;
    }
    .iconcommon {
      position: absolute;
      top: 80px;
      right: 70px;
      font-size: 60px;
      color: blue;
    }
    .iconcommon2 {
      position: absolute;
      top: 80px;
      right: 70px;
      font-size: 60px;
      color: red;
    }
    .w70 {
      display: inline-block;
      width: 70px;
      text-align: right;
    }
    .condition-container {
      display: inline-block;
      margin-top: 10px;
    }
    .iconcolor1 {
      color: #409eff;
    }
    .color_l {
      color: #67c23a;
    }
    .color_red {
      color: #f56c6c;
    }
    .colorBlue {
      color: #409eff;
    }
    .mb10 {
      margin-bottom: 20px;
    }
    .ml-upload {
      display: inline-block;
      margin-left: 10px;
      vertical-align: bottom;
      margin-right: 10px;
    }
  }
</style>
